package com.xinxing.learning.security.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.authentication.RememberMeServices;
import org.springframework.security.web.authentication.rememberme.JdbcTokenRepositoryImpl;
import org.springframework.security.web.authentication.rememberme.PersistentTokenBasedRememberMeServices;
import org.springframework.security.web.authentication.rememberme.PersistentTokenRepository;

import javax.sql.DataSource;
import java.util.UUID;

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    private final DataSource dataSource;

    public SecurityConfig(DataSource dataSource) {
        this.dataSource = dataSource;
    }

    @Bean
    public UserDetailsService userDetailsService() {
        InMemoryUserDetailsManager inMemoryUserDetailsManager = new InMemoryUserDetailsManager();
        inMemoryUserDetailsManager.createUser(User.withUsername("root").password("{noop}123").roles("admin", "supper").build());
        return inMemoryUserDetailsManager;
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService());
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                // 登录请求不需要认证
                // .mvcMatchers("/login").permitAll()
                // 指定哪些资源开启记住我功能 其他资源不开启记住我功能 提高安全性
                // .mvcMatchers("/index").rememberMe()
                // 所有请求都需要认证
                .anyRequest().authenticated()
                .and()
                // 表单认证方式
                .formLogin()
                .and()
                // 开启记住我功能
                .rememberMe()
                // 指定rememberMeServices的实现 提高安全性
                .rememberMeServices(rememberMeServices())
                .tokenRepository(persistentTokenRepository())
                // 自定义请求参数key
                // .rememberMeParameter("remember-me")
                // 不管前端是否选择记住我 认证成功后都会记住我
                // .alwaysRemember(true)
                .and()
                // 禁用跨域
                .csrf().disable();
    }

    @Bean
    public PersistentTokenRepository persistentTokenRepository() {
        JdbcTokenRepositoryImpl jdbcTokenRepository = new JdbcTokenRepositoryImpl();
        jdbcTokenRepository.setDataSource(this.dataSource);
        // 第一次启动的时候 会在数据库自动创建持久化记住我token的表，之后启动就不需要再进行创建表了 如果还是为true会启动报错 Table 'persistent_logins' already exists
        // 关闭即可
        // jdbcTokenRepository.setCreateTableOnStartup(true);
        jdbcTokenRepository.setCreateTableOnStartup(false);
        return jdbcTokenRepository;
    }

    /**
     * 记住我的token生成方式发生了改变
     * 每次访问通过记住我实现认证通过后都会更新记住我的token 以提高安全性
     *
     * @return
     */
    @Bean
    public RememberMeServices rememberMeServices() {
        return new PersistentTokenBasedRememberMeServices(UUID.randomUUID().toString(), userDetailsService(), persistentTokenRepository());
    }
}
